package com.yanze.controller;

import com.yanze.pojo.BaseJsonResult;
import com.yanze.pojo.User;
import com.yanze.utils.JsonUtils;
import com.yanze.utils.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("redis")
public class RedisController {

    @Autowired
    private StringRedisTemplate strRedis;

    @Autowired
    private RedisOperator redis;

    @RequestMapping("/test")
    public BaseJsonResult test() {
        User user = new User();
        user.setName("白泽丶");
        user.setAge(20);
        user.setBirthday(new Date());
        user.setPassword("123456");
        user.setDesc("机智如我！");

        strRedis.opsForValue().set("User:json", JsonUtils.objectToJson(user));

        User userJson = JsonUtils.jsonToPojo(strRedis.opsForValue().get("User:json"), User.class);

        return BaseJsonResult.ok(userJson);
    }

    @RequestMapping("/getList")
    public BaseJsonResult getList() {
        List<User> users = new ArrayList<>();

        User user1 = new User("yanze", "123456", 18, new Date(), "人生得意须尽欢");
        User user2 = new User("白泽", "123456", 20, new Date(), "莫使金樽空对月");
        User user3 = new User("君子彦", "123456", 22, new Date(), "与君歌一曲");

        users.add(user1);
        users.add(user2);
        users.add(user3);

        redis.set("userList:json", JsonUtils.objectToJson(users));

        List<User> temp = JsonUtils.jsonToList(redis.get("userList:json"), User.class);

        return BaseJsonResult.ok(temp);
    }

}
